package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"time"
)

type AixinwuCoinTransfer struct {
	beego.Controller
}

func (c *AixinwuCoinTransfer) Post() {
	beego.Debug("add user")
	request := TypeAixinwuCoinTransferReq{}
	body := c.Ctx.Input.CopyBody(beego.AppConfig.DefaultInt64("bodybuffer", 1024*1024))
	beego.Info("Post Body is:", string(body))
	err := json.Unmarshal(body, &request)
	ErrReport(err)
	if err != nil {
		c.Abort("400")
		return
	}
	response := TypeRegularResp{
		MataData: GenMataData(),
	}
	// check token
	tInfo := ParseToken(request.Token)
	if tInfo.UserID <= 0 || request.Cash <= 0 {
		c.Abort("400")
		return
	}
	o := orm.NewOrm()
	for {
		err := o.Begin()
		if err != nil {
			ErrReport(err)
			response.Status = GenStatus(StatusCodeDatabaseErr)
			break
		}
		giverAixinwuID := TransferLocalIDtoAixinwuID(tInfo.UserID)
		if giverAixinwuID == 0 {
			response.Status = GenStatus(StautsCodeNotBindToAixinwuAccount)
			break
		}
		giverCash := TypeAixinwuCustomCash{
			User_id: giverAixinwuID,
		}
		err = o.Read(&giverCash)
		if err != nil {
			ErrReport(err)
			response.Status = GenStatus(StatusCodeDatabaseErr)
			break
		}
		giverAixinwuAccount := TypeAixinwuJaccountInfo{
			Customer_id: giverCash.User_id,
		}
		err = o.Read(&giverAixinwuAccount, "customer_id")
		ErrReport(err)
		// parse receiver
		receiverCash := TypeAixinwuCustomCash{}
		if request.JaccountID != "" {
			jacinfo := TypeAixinwuJaccountInfo{
				Jaccount_id: request.JaccountID,
			}
			err = o.Read(&jacinfo, "jaccount_id")
			if err != nil {
				ErrReport(err)
				response.Status = GenStatus(StatusCodeDatabaseErr)
				break
			}
			receiverCash.User_id = jacinfo.Customer_id
		}
		err = o.Read(&receiverCash)
		if err != nil {
			ErrReport(err)
			response.Status = GenStatus(StatusCodeDatabaseErr)
			break
		}
		if giverCash.User_id == receiverCash.User_id {
			response.Status = GenStatus(StautsCodeCannottransferToself)
			break
		}
		receiverAixinwuAccount := TypeAixinwuJaccountInfo{
			Customer_id: receiverCash.User_id,
		}
		err = o.Read(&receiverAixinwuAccount, "customer_id")
		ErrReport(err)
		if request.ReceiverID != 0 {
			receiverCash.User_id = TransferLocalIDtoAixinwuID(request.ReceiverID)
		}
		if request.ReceiverName != "" {
			userInfo, err := GetUserInfo(request.ReceiverName)
			receiverCash.User_id = TransferLocalIDtoAixinwuID(userInfo.ID)
			if err != nil {
				ErrReport(err)
				response.Status = GenStatus(StatusCodeDatabaseErr)
				break
			}
		}
		// Check remain money
		if giverCash.Total < request.Cash {
			response.Status = GenStatus(StatusCodeNotEnoughMoney)
			break
		}
		// perform transfer
		giverCash.Total -= request.Cash
		receiverCash.Total += request.Cash
		_, err = o.Update(&giverCash)
		if err != nil {
			ErrReport(err)
			response.Status = GenStatus(StatusCodeDatabaseErr)
			break
		}
		_, err = o.Update(&receiverCash)
		if err != nil {
			ErrReport(err)
			response.Status = GenStatus(StatusCodeDatabaseErr)
			break
		}
		// make record
		giverLog := TypeAixinwuCashLog{
			Datetime:    time.Now(),
			Customer_id: giverCash.User_id,
			Admin_id:    0,
			Change_num:  -request.Cash,
			Reason:      fmt.Sprintf("爱心币转帐 %v 至用户 %s", request.Cash, receiverAixinwuAccount.Jaccount_id),
		}
		_, err = o.Insert(&giverLog)
		if err != nil {
			ErrReport(err)
			response.Status = GenStatus(StatusCodeDatabaseErr)
			break
		}
		receiverLog := TypeAixinwuCashLog{
			Datetime:    time.Now(),
			Customer_id: receiverCash.User_id,
			Admin_id:    0,
			Change_num:  request.Cash,
			Reason:      fmt.Sprintf("从用户 %s 收到转帐%v", giverAixinwuAccount.Jaccount_id, request.Cash),
		}
		_, err = o.Insert(&receiverLog)
		if err != nil {
			ErrReport(err)
			response.Status = GenStatus(StatusCodeDatabaseErr)
			break
		}
		break
	}
	if response.Status.Code == StatusCodeOK {
		ErrReport(o.Commit())
	} else {
		ErrReport(o.Rollback())
	}

	c.Data["json"] = response
	c.ServeJSON()
}
